package demo.stan;

import com.google.common.collect.ImmutableMap;
import demo.java.net.HttpDemo;
import demo.vo.http.ResponseVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 国内文本
 * 国际文本
 * 国内营销
 */
public class TxSender {

    private int appId = 1400188466;

    private String appkey = "39816521acfa3f38b844e3fc002ee874XX";

    private int tmpId = 286113;

    private String signature = "喜马拉雅XX";

    @Test
    public void sendMainladText() {
        try {
            ResponseVo vo = singleSendText("18217006685", Arrays.asList("大江东去，浪淘尽，千古风流人物。\n" +
                    "故垒西边，人道是，三国周郎赤壁。\n" +
                    "乱石穿空，惊涛拍岸，卷起千堆雪。\n" +
                    "江山如画，一时多少豪杰。\n" +
                    "遥想公瑾当年，小乔初嫁了，雄姿英发。\n" +
                    "羽扇纶巾，谈笑间，樯橹灰飞烟灭。\n" +
                    "故国神游，多情应笑我，早生华发。\n" +
                    "人生如梦，一尊还酹江月。"));
            System.err.println(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Test
    public void sendMainlandVoice() {
        try {
            ResponseVo vo = sendMainlandVoice("18217006685", "大浪淘沙");
            System.err.println(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 语音电话
     * <p>
     * https://cloud.tencent.com/document/product/1128/37723
     *
     * @param mobile
     * @param message
     * @return
     */
    protected ResponseVo sendMainlandVoice(String mobile, String message) throws IOException {
        String zone = "86";
        long now = System.currentTimeMillis() / 1000;
        long random = (new Random(now)).nextInt(900000) + 100000;
        ImmutableMap<String, Object> body = ImmutableMap.<String, Object>builder()
                .put("tpl_id", tmpId)
                .put("params", Collections.singletonList(message))
                .put("playtimes", 2) // 默认播放2次
                .put("sig", calculateSignature(appkey, random, now, mobile))
                .put("tel", new Tel(zone, mobile))
                .put("time", now)
                .put("ext", "")
                .build();

        String url = "https://cloud.tim.qq.com/v5/tlsvoicesvr/sendtvoice?sdkappid=" + appId + "&random=" + random;
        ResponseVo vo = HttpDemo.requestAsJson(url, body, RequestMethod.POST);
        return vo;
    }


    private ResponseVo singleSendText(String mobile, List<String> params) throws IOException {
        String zone = "86";
        long now = System.currentTimeMillis() / 1000;
        long random = (new Random(now)).nextInt(900000) + 100000;
        ImmutableMap<String, Object> body = ImmutableMap.<String, Object>builder()
                .put("tel", new Tel(zone, mobile))
                .put("sig", calculateSignature(appkey, random, now, mobile))
                .put("tpl_id", tmpId)
                .put("params", params)
                .put("sign", signature)
                .put("time", now)
                .put("extend", "")
                .put("ext", "").build();

        String url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=" + appId + "&random=" + random;
        return HttpDemo.requestAsJson(url, body, RequestMethod.POST);
    }

    private ResponseVo batchSendMainText(List<String> mobiles, List<String> params) throws IOException {
        String zone = "86";
        List<Tel> tels = new ArrayList<>(mobiles.size());
        mobiles.forEach(mobile -> tels.add(new Tel(zone, mobile)));
        long now = System.currentTimeMillis() / 1000;
        long random = (new Random(now)).nextInt(900000) + 100000;
        ImmutableMap<String, Object> body = ImmutableMap.<String, Object>builder()
                .put("tel", tels)
                .put("sig", calculateSignature(appkey, random, now, mobiles))
                .put("tpl_id", tmpId)
                .put("params", params)
                .put("sign", signature)
                .put("time", now)
                .put("extend", "")
                .put("ext", "").build();

        String url = "https://yun.tim.qq.com/v5/tlssmssvr/sendmultisms2?sdkappid=" + appId + "&random=" + random;
        return HttpDemo.requestAsJson(url, body, RequestMethod.POST);
    }


    private static class Tel {

        private String nationcode;

        private String mobile;

        public Tel(String nationcode, String mobile) {
            this.nationcode = nationcode;
            this.mobile = mobile;
        }

        public String getNationcode() {
            return nationcode;
        }

        public void setNationcode(String nationcode) {
            this.nationcode = nationcode;
        }

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
    }


    private static class SingleSendResult {
        /**
         * 返回0表示成功，其他表示错误
         */
        private Integer result;
        /**
         * 错误消息，成功返回 "OK"
         */
        private String errmsg;

        private String ext;
        /**
         * 唯一ID
         */
        private String sid;
        /**
         * 计费：单位分
         */
        private int fee;
        /**
         * 地区码
         */
        private String isocode;

        public Integer getResult() {
            return result;
        }

        public void setResult(Integer result) {
            this.result = result;
        }

        public String getErrmsg() {
            return errmsg;
        }

        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }

        public String getExt() {
            return ext;
        }

        public void setExt(String ext) {
            this.ext = ext;
        }

        public String getSid() {
            return sid;
        }

        public void setSid(String sid) {
            this.sid = sid;
        }

        public int getFee() {
            return fee;
        }

        public void setFee(int fee) {
            this.fee = fee;
        }

        public String getIsocode() {
            return isocode;
        }

        public void setIsocode(String isocode) {
            this.isocode = isocode;
        }
    }


    private static class BatchSendResult {
        /**
         * 返回0表示成功，其他表示错误
         */
        public Integer result;
        /**
         * 错误消息，成功返回 "OK"
         */
        public String errMsg;

        public String ext;

        public ArrayList<Detail> detail;
    }


    private static class Detail {

        public int result;

        public String errmsg = "";

        public String mobile = "";

        public String nationcode = "";

        public String sid = "";

        public int fee = 0;

    }

    private static String calculateSignature(String appkey, long random, long time,
                                             String phoneNumber) {
        StringBuilder buffer = new StringBuilder("appkey=")
                .append(appkey)
                .append("&random=")
                .append(random)
                .append("&time=")
                .append(time)
                .append("&mobile=")
                .append(phoneNumber);
        return DigestUtils.sha256Hex(buffer.toString());
    }

    public static String calculateSignature(String appkey, long random, long time, List<String> mobiles) {
        StringBuffer buffer = new StringBuffer("appkey=")
                .append(appkey)
                .append("&random=")
                .append(random)
                .append("&time=")
                .append(time)
                .append("&mobile=")
                .append(String.join(",", mobiles));
        return DigestUtils.sha256Hex(buffer.toString());
    }
}